<?php

namespace tmcore\services\notice\wechat;

use app\common\enum\MsgEnum;
use app\common\jobs\notice\WechatTemplateJob;
use app\common\model\notice\UserNoticeLog;
use tmcore\services\notice\BaseNotice;
use GuzzleHttp\Exception\GuzzleException;

class WechatSendService extends BaseNotice
{
    /**
     * 发送消息
     * @param array $config
     * @param array $params ['uid' => '用户id', 'openid' => 'openid', 'expire_time' => '验证码过期时间', 'template' => '微信模板参数', 'extend' => '扩展参数']
     * @param bool $is_async
     * @return bool|mixed
     */
    public function send($config, $params, $is_async = false) {

        if(empty($params['openid']) || empty($params['template'])) return self::setError('参数校验失败');
        if($config['is_captcha'] && empty($params['template']['code'])) return self::setError('参数校验失败');

        $notice_log = UserNoticeLog::create([
            'scene'       => $config['scene'],
            'msg_token'   => $config['msg_token'],
            'uid'         => $params['uid']??0,
            'account'     => $params['openid'],
            'title'       => $config['name'],
            'code'        => $config['is_captcha']?$params['template']['code']:'',
            'content'     => $this->getContent($params['template'], $config['wechat_template']['content']??''),
            'error'       => '',
            'notice_type' => $config['type'],
            'send_type'   => MsgEnum::WX_OA_TYPE,
            'status'      => 0,
            'is_read'     => 0,
            'is_captcha'  => $config['is_captcha'],
            'expire_time' => $params['expire_time']??time()+900,
        ]);

        if(empty($notice_log['id'])) return self::setError('添加日志失败');

        if($is_async) {
            //加入异步队列
            WechatTemplateJob::pushJob([
                'job' => 'wechatTemplateJob',
                'data' => [
                    'openid' => $params['openid'],
                    'templateId' => $config['wechat_template']['templateId']??'',
                    'templateParams' => [
                        'url' => $params['extend']['url']??($config['wechat_template']['url']??''),
                        'mnp_appid' => $params['extend']['mnp_appid']??'',
                        'mnp_page' => $params['extend']['mnp_page']??'',
                        'data' => $params['template']
                    ],
                    'id' => $notice_log['id']
                ]
            ]);
            return true;
        } else {
            return $this->sendWechatTemplate(
                $params['openid'],
                $config['wechat_template']['templateId']??'',
                [
                    'url' => $params['extend']['url']??($config['wechat_template']['url']??''),
                    'mnp_appid' => $params['extend']['mnp_appid']??'',
                    'mnp_page' => $params['extend']['mnp_page']??'',
                    'data' => $params['template']
                ],
                $notice_log['id']
            );
        }
    }

    /**
     * 发送微信模板消息
     * @param $openid
     * @param $templateId
     * @param $templateParams
     * @param $log_id
     * @return bool
     */
    public function sendWechatTemplate($openid, $templateId, $templateParams, $log_id) {
        try {
            (new WechatTemplateService)->sendTemplate([
                'openid' => $openid,
                'template_id' => $templateId,
                'url' => $templateParams['url'],
                'mnp_appid' => $templateParams['mnp_appid']??'',
                'mnp_page' => $templateParams['mnp_page']??'',
                'data' => $templateParams['data']
            ]);

            $this->sendSuccess($log_id);
            return true;
        } catch (GuzzleException $e) {
            $this->sendFail($log_id, $e->getMessage());
            return self::setError($e->getMessage());
        } catch (\Exception $e) {
            $this->sendFail($log_id, $e->getMessage());
            return self::setError($e->getMessage());
        }
    }
}